package myjava.p_classLoader;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 自定义文件系统类加载器
 * @author 尚学堂高淇 www.sxt.cn
 *
 */
public class FileSystemClassLoader extends ClassLoader {

	private String rootDir;

	public FileSystemClassLoader(String rootDir){
		this.rootDir = rootDir;
	}

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		//输入流，通过类的全限定名称加载文件到字节数组
		byte[] classDate = getClassData(name);
		if (classDate != null) {
			//defineClass方法将字节数组数据 转为 字节码对象
			return defineClass(name, classDate, 0, classDate.length);
		}
		return super.findClass(name);
	}

	/**
	 * 加载指定名称的Java字节码文件，返回字节数组
	 * @param classname
	 * @return
	 */
	private byte[] getClassData(String classname){
		String path = rootDir +"/"+ classname.replace('.', '/')+".class";

		try (InputStream is = new FileInputStream(path);
			 ByteArrayOutputStream baos = new ByteArrayOutputStream()){
			byte[] buffer = new byte[1024];
			int temp=0;
			while((temp=is.read(buffer))!=-1){
				baos.write(buffer, 0, temp);
			}

			return baos.toByteArray();
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

}
